package client;

import java.io.File;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import entity.LogRec;
import entity.MatchedLogRec;
import exceptions.MatchDataException;

public class DataMatcher {
	private String loginsFileName;
	private String labIP;
	
	public DataMatcher(String loginsFileName,String labIP) {
		this.loginsFileName=loginsFileName;
		this.labIP=labIP;
	}

	public List<MatchedLogRec> matchLogs(List<LogRec> list) throws MatchDataException{
		List<LogRec> login = new ArrayList<LogRec>();
		List<LogRec> logout = new ArrayList<LogRec>();
		
		for (LogRec r : list) {
			short logType = r.getLogType();
			if(logType==7){
				login.add(r);
			}
			if(logType==8){
				logout.add(r);
			}
		}
		
		List<MatchedLogRec> listM=new ArrayList<MatchedLogRec>();
		Iterator<LogRec> outIter = logout.iterator();
		while(outIter.hasNext()){
			LogRec outR = outIter.next();
			for(int i=0;i<login.size();i++){
				LogRec inR=login.get(i);
				if(inR.getLogName().equals(outR.getLogName())&&inR.getPid()==outR.getPid()
						&&inR.getLogIP().equals(outR.getLogIP())){
					MatchedLogRec mlr = new MatchedLogRec();
					mlr.setLabIP(labIP);
					mlr.setLogName(inR.getLogName());
					mlr.setLogIP(inR.getLogIP());
					mlr.setLoginTime(inR.getLogTime());
					mlr.setLogoutTime(outR.getLogTime());
					mlr.setDurations(outR.getLogTime()-inR.getLogTime());
					listM.add(mlr);
					login.remove(i);
					outIter.remove();
					break;
				}
			}
		}
		
		//保存未匹配的到文件
		List<LogRec> notMatch = new ArrayList<LogRec>();//再匹配时将未匹配的数据存入此list，匹配时就可不使用删除的方法
		notMatch=login;
		if(!notMatch.isEmpty()){
			try {
				FileOutputStream fout = new FileOutputStream(new File(loginsFileName));
				ObjectOutputStream out = new ObjectOutputStream(fout);
				out.writeObject(notMatch);
				out.close();
			} catch (Exception e) {
				e.printStackTrace();
				throw new MatchDataException(e);
			}
		}
		
		return listM;
	}
}
